//
//  AppDelegate.m
//  HuanXin
//
//  Created by monkey on 2019/7/8.
//  Copyright © 2019 itcast. All rights reserved.
//

#import <Hyphenate/Hyphenate.h>
#import <SVProgressHUD/SVProgressHUD.h>

#import "AppDelegate.h"

#import "XGMainViewController.h"
#import "XGLoginViewController.h"

#import "XGFriendRequestNotificationCenter.h"

@interface AppDelegate () <EMClientDelegate>

@end

@implementation AppDelegate

#pragma mark - AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self initializeSetting];
    DEBUG_Log(@"%@",NSHomeDirectory());
    _window = [[UIWindow alloc] init];
    _window.backgroundColor = [UIColor whiteColor];
    _window.rootViewController = [self rootViewController];
    [_window makeKeyAndVisible];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [[EMClient sharedClient] applicationDidEnterBackground:application];
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [[EMClient sharedClient] applicationWillEnterForeground:application];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application
{
    [[EMClient sharedClient] removeDelegate:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 事件监听

/// 通知监听切换根控制器
- (void)switchApplicationRootViewController:(NSNotification *)notification
{
    NSString *className = notification.userInfo[XGRootViewControllerClassNameKey];
    UIViewController *viewController = [[NSClassFromString(className) alloc] init];
    _window.rootViewController = viewController;
}

#pragma mark - EMClientDelegate

// 自动登录返回结果
- (void)autoLoginDidCompleteWithError:(EMError *)error
{
    if (error != nil) {
        DEBUG_Log(@"%@",error.errorDescription);
        return;
    }
    
    DEBUG_Log(@"自动登录成功");
}

// SDK连接服务器的状态变化时会接收到该回调
- (void)connectionStateDidChange:(EMConnectionState)aConnectionState
{
    DEBUG_Log(@"自动重连");
}

// 当前登录账号在其它设备登录时会接收到该回调
- (void)userAccountDidLoginFromOtherDevice
{
    [self logOutWithMessage:@"该账号已在别处登录,请重新登录" className:@"XGLoginViewController"];
}

// 当前登录账号已经被从服务器端删除时会收到该回调
- (void)userAccountDidRemoveFromServer
{
    [self logOutWithMessage:@"该账号已在服务器被删除" className:@"XGLoginViewController"];
}

#pragma mark - 其他方法

// 返回根控制器
- (UIViewController *)rootViewController
{
    if ([EMClient sharedClient].isAutoLogin) {
        return [[XGMainViewController alloc] init];
    }
    
    return [[XGLoginViewController alloc] init];
}

/// 初始化设置
- (void)initializeSetting
{
    // appkey替换成自己在环信管理后台注册应用中的appkey
    EMOptions *options = [EMOptions optionsWithAppkey:@"1152190708083652#huanxin"];
    // apnsCertName是证书名称，可以先传nil，等后期配置apns推送时在传入证书名称
    options.apnsCertName = nil;
    options.enableConsoleLog = YES;
    [[EMClient sharedClient] initializeSDKWithOptions:options];
    [[EMClient sharedClient] addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    // 设置SVProgressHUD
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setForegroundColor:[UIColor red:31 green:185 blue:34 alpha:1.f]];
    [SVProgressHUD setMaximumDismissTimeInterval:2];
    
    // 注册通知监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(switchApplicationRootViewController:) name:XGSwitchApplicationRootViewControllerNotification object:nil];
    
    [XGFriendRequestNotificationCenter shared];
}

- (void)logOutWithMessage:(NSString *)message className:(NSString *)className
{
    // 主动退出传YES 被动退出NO
    [[EMClient sharedClient] logout:NO completion:^(EMError *aError) {
        if (aError != nil) {
            DEBUG_Log(@"退出登录失败 %@",aError.errorDescription);
            return;
        }
        
        [SVProgressHUD showErrorWithStatus:message];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 切换根控制器
            [[NSNotificationCenter defaultCenter] postNotificationName:XGSwitchApplicationRootViewControllerNotification object:nil userInfo:@{XGRootViewControllerClassNameKey: className}];
        });
    }];
}

@end
